﻿// controller to handle the edit process of the user's profile
angular.module('app.user').controller('UserProfileEditController', [
	'$scope', '$state', 'authService', 'notify', '$window',
	function ($scope, $state, authService, notify, $window) {
		'use strict'

		var instance = this;
		// initialize the model
		$scope.model = { 
			currentPassword: '', 
			newPassword: '', 
			confirmNewPassword: '', 
			message: ''
		};
	
		// handle the submit change password response
		this.handleSubmitChangePassword = function (reply) {
			// clear the model fields
			$scope.model.currentPassword = '';
			$scope.model.newPassword = '';
			$scope.model.confirmNewPassword = '';
			// if successful, go back to the previous page and notify the user
			if (reply.data.Successful) {
				$window.history.back();
				notify.success('Password successfully changed');
			}
			else {
				// notify the user of the error
				notify.error(reply.data.Message);
			}
		};

		$scope.submitChangePassword = function () {
			// validate the model and notify the user of any warning messages
			if ($scope.model.currentPassword.length < 1) {
				notify.warning('Please enter current password');
			}
			else if ($scope.model.newPassword.length < 1) {
				notify.warning('Please enter new password');
			} 
			else if ($scope.model.confirmNewPassword.length < 1) {
				notify.warning('Please confirm your new password');
			} 
			else if ($scope.model.newPassword !== $scope.model.confirmNewPassword) {
				notify.warning('New Passwords do not match!');
			} 
			else {
				// model is valid, submit the change password request
				authService.changePassword($scope.model.currentPassword, $scope.model.newPassword)
					.then(instance.handleSubmitChangePassword);
			}
		};

		// cancle the change password process
		$scope.cancelPasswordChange = function () {
			// clear the fields and go back to the previous page
			$scope.model.currentPassword = '';
			$scope.model.newPassword = '';
			$scope.model.confirmNewPassword = '';
			$window.history.back();
		}
	}]);